const express = require('express');
const vertoken = require('./public/token')
const expressJWT = require('express-jwt')
const app = express();

// 注册全局解析中间件
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//使用 /static 作为前缀来加载 public 文件夹下的文件
app.use('/static', express.static(__dirname + '/public'));

const loginapi = require('./api/loginapi');
app.use('/login',loginapi);
const superapi = require('./api/superapi');
app.use('/super',superapi);
const uploadapi = require('./api/uploadapi');
app.use('/upload',uploadapi)
const pubapi = require('./api/pubapi');
app.use('/public',pubapi)


const departmentapi = require('./operationapi/departmentapi')
app.use('/department',departmentapi);
const employeeapi = require('./operationapi/employeeapi')
app.use('/employee',employeeapi);
const procurerecordapi = require('./operationapi/procure_record_api')
app.use('/procurerecord',procurerecordapi);
const procurerequestapi = require('./operationapi/procure_request_api')
app.use('/procurerequest',procurerequestapi);
const recordapi = require('./operationapi/recordapi')
app.use('/record',recordapi);
const retgoodsapi = require('./operationapi/retgoodsapi')
app.use('/retgoods',retgoodsapi);
const stockapi = require('./operationapi/stockapi')
app.use('/stock',stockapi);
const supplieapi = require('./operationapi/supplieapi')
app.use('/supplie',supplieapi);
const warehouseapi = require('./operationapi/warehouseapi')
app.use('/warehouse',warehouseapi);
const messageapi = require('./operationapi/messageapi')
app.use('/message',messageapi);


// 解析token获取用户信息
app.use(function(req, res, next) {
  var token = req.headers['authorization'];
  if(token == undefined){
    return next();
  }else{
    vertoken.verToken(token).then((data)=> {
      req.data = data;
      return next();
    }).catch((error)=>{
      return next();
    })
  }
});

//验证token是否过期并规定哪些路由不用验证
app.use(expressJWT({
  secret: 'mes_qdhd_mobile_xhykjyxgs'
}).unless({
  path: ['/login']//除了这个地址，其他的URL都需要验证
}));
//当token失效返回提示信息
app.use(function(err, req, res, next) {
  if (err.status == 401) {
    return res.status(401).send('token失效');
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log('express server listen at http://localhost:'+PORT);
});
